import axios from "axios";
import { ElMessage } from "element-plus";
const instance = axios.create({
  baseURL: "/api",
  timeout: 5000,
});

instance.interceptors.request.use(
  (config) => {
    //Content-Typ 参数转换
    // if (
    //   config.url === "/sendSMS" ||
    //   config.url === "/wechatUsers/PCLogin" ||
    //   config.url == "/shop/carts/add"
    // ) {
    //   let config: any;
    //   config.headers["Content-Type"] = "application/x-www-form-urlencoded";
    // }
    let token = localStorage.getItem("token");
    if (token && config.headers) {
      // typeof config.headers.set == "function" &&
      // config.headers.set("x-auth-token", token);
      (config.headers.set as Function)(
        "x-auth-token",
        localStorage.getItem("token")
      );
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

instance.interceptors.response.use(
  (res) => {
    //统一处理
    if (res.data.code == 401) {
      ElMessage.error("登录状态失效,请重新登录");
    } else if (res.data.code != 0 && res.data.code != 400) {
      ElMessage.error(res.data.message);
    }
    return res.data;
  },
  (err) => {
    return Promise.reject(err);
  }
);

export default instance;
